import { Controller } from 'egg'

// const find = require('lodash-es')

const formatMenu = (list) => {
  const result: any[] = []
  list.forEach((item) => {
    const value = item.dataValues ?? item
    if (!value?.parent) {
      result.splice(value.order - 1, 0, value)
    }

    else {
      result.forEach((r) => {
        if (r.id === String(value.parent)) {
          if (r.children)
            r.children.splice(value.order - 1, 0, value)

          else
            r.children = [value]
        }
      })
    }
  })
  return result
}

export default class MenuController extends Controller {
  // 全查
  async list() {
    const { ctx } = this
    const menuList = await ctx.service.menu.list()
    ctx.body = formatMenu(menuList)
  }

  // 单查 /menu/findOne?id=x
  async findOne() {
    const { ctx } = this
    const id = ctx.query.id
    const result = await ctx.model.Menu.findByPk(id)
    ctx.body = result
  }

  // 增
  async create() {
    const { ctx } = this
    const body = ctx.request.body
    // TODO validate
    const result = await ctx.model.Menu.create(body)
    ctx.status = 201
    ctx.body = result
  }

  // 改
  async update() {
    const { ctx } = this
    ctx.logger.info('id', ctx.query.id)
    const instance = await ctx.model.Menu.findByPk(ctx.query.id)
    if (!instance) {
      ctx.status = 404
      ctx.body = '未查到需要修改的菜单'
    }

    else {
      const { title } = ctx.request.body
      await instance.update({ title })
      ctx.body = instance
    }
  }

  // 删
  async destroy() {
    const { ctx } = this
    const id = ctx.query.id
    const instance = await ctx.model.Menu.findByPk(id)

    if (!instance) {
      ctx.status = 404
      ctx.body = '未查到需要删除的菜单'
    }

    else {
      await instance.destroy()
      ctx.status = 200
      ctx.body = '删除成功'
    }
  }
}